/**
 * 
 */
package com.ruyipu.forum.base;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;

/**
 * @author donald
 *
 */
public class FileWriter {
	public static final String TAG = FileWriter.class.getSimpleName();
	public static final String NAME = FileWriter.class.getName();
	
	private FileWriter(){}
	
	static{
		makeDir(Constants.DIR_BASE);
		makeDir(Constants.DIR_JSON);
		makeDir(Constants.DIR_IMAGE);
	}
	
	public static void write(String fileName, String content) {
		File file = new File(fileName);
		if(file.exists()) {
			file.delete();
		}
		try {
			OutputStream os = new FileOutputStream(file);
			OutputStreamWriter writer = new OutputStreamWriter(os);
			writer.write(content);
			writer.close();
		} catch (FileNotFoundException e) {
			MyLog.e(TAG, e);
		} catch (IOException e) {
			MyLog.e(TAG, e);
		}
	}
	
	public static String fixJSONFileName(String url) {
		String fileName = MD5.getMD5(url.getBytes());
		fileName = Constants.DIR_JSON + fileName.substring(0, 6) + ".json"; 
		return fileName;
	}
	
	public static void makeDir(String dirPath) {
		File file = new File(dirPath);
		if(!file.exists()) {
			if(!file.mkdirs()) {
				MyLog.e(TAG, "Could not make dir " + dirPath);
			}
		}
	}
			
}
